var app = angular.module("app", [ 'base', 'baseDirective' ]);
app.controller('ctrl', [ '$scope', 'baseService', 'ArrayToolService', '$filter', function($scope, baseService, ArrayToolService, $filter) {
	var filter = $filter('filter');
	$scope.ArrayTool = ArrayToolService;

	var ifremeCssUrlMap = {
		"pc" : '../../assets/js/plugins/ueditor/themes/pcframe.css',
		"pc_vue" : '../../assets/js/plugins/ueditor/themes/pcframe.css',
		"mobile" : '../../assets/js/plugins/ueditor/themes/mobileFormIframe.css',
		"pc_iview" : '../../assets/iview/css/iview.css',
	};

	$scope.init = function() {
		// uedtor的配置
		$scope.editorConfig = {
			// toolbars : [ [ 'source', 'undo', 'redo', 'bold', 'italic',
			// 'removeformat', 'formatmatch', 'autotypeset', 'blockquote',
			// 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist',
			// 'insertunorderedlist', '|', 'selectTemplate' ] ],
			initialFrameHeight : window.innerHeight - 260,
			enableAutoSave : false,
			autoHeightEnabled : false,
			allHtmlEnabled : true,
			focus : true,
			iframeCssUrl : ifremeCssUrlMap[formType],// 加入css
		};
		
		window.setTimeout(function(){
		// 支持拖拽
			var editor = $scope.abEditor;
			$(".panel-body",editor.document).each(function(index,item){
				Sortable.create(item, {
					handle: '.form-item-label',
					draggable: '.form-item',
					onUpdate:function(){
						 console.info(index+"column sort update")
					}
				})
			})
		},1000);
	};

	$scope.$on("afterLoadEvent", function(event, data) {
		$scope.data.type = formType;
		console.info($scope.data.html);
		if (formType == "pc_vue" || formType == "pc_iview") {
			$scope.data.html = $scope.data.html.replace(/<ab-sub-scope-tr([\s|\S]*?)<\/ab-sub-scope-tr>/g, '<tr scope=""$1</tr>');
		}
	});

	window.editorBeforeSaveEvent = function(event, data) {
		console.info("修改前：" + $scope.data.html);
		if (formType == "pc_vue" || formType == "pc_iview") {
			$scope.data.html = $scope.data.html.replace(/<tr scope=""([\s|\S]*?)<\/tr>/g, '<ab-sub-scope-tr$1</ab-sub-scope-tr>');
		}
		console.info("修改后：" + $scope.data.html);
	};

	$scope.$on("afterSaveEvent", function(event, data) {
		if (window.opener && window.opener.reloadGrid) {
			window.opener.reloadGrid();
		}
		if (!data.r) {
			window.close();
		} else {
			window.location.reload();
		}
	});

	/**
	 * 预览
	 */
	$scope.preview = function(isBlank) {
		var previewUrlMap = {
			"pc" : 'formDefPreview.html',
			"pc_vue" : 'vueFormDefPreview.html',
			"pc_iview" : window.__ctx_pc_iview + '/bpm/form/preview',
			"mobile" : window.__ctx_mb + '/#/bpm/preview',
		};

		if (!previewUrlMap[formType]) {
			$.Dialog.alert(formType + "类型表单暂不支持预览");
			return;
		}
		if (isBlank) {
			window.open(previewUrlMap[formType] + "?key=" + $scope.data.key, "_blank");
			return;
		}
		
		var html =  $scope.data.html;
		if (formType == "pc_vue" || formType == "pc_iview") {
			html = html.replace(/<tr scope=""([\s|\S]*?)<\/tr>/g, '<ab-sub-scope-tr$1</ab-sub-scope-tr>');
		}

		var conf = {
			height : 0,
			title : "预览",
			url : previewUrlMap[formType] + "?key=" + $scope.data.key,
			passData : {
				html : html
			}
		};
		$.Dialog.open(conf);
	};

	$scope.$watch("data.boKey", function(newValue, oldValue) {
		if (!newValue || newValue === oldValue) {
			return;
		}
		// 加载boTree
		// 请求参数
		var params = {
			boKey : newValue
		};
		var callBack = function(event, treeId, treeNode) {
			if(treeNode.nodeType=="table"){
				var tableName = treeNode.relationType=="main" ? "":treeNode.key;
				$scope.selectTemplate(tableName);
				return;
			}
			var isMain = treeNode.getParentNode().relationType=="main";
		
			var editor = $scope.abEditor;
			var url = __ctx + "/form/formDef/genColumnHtml";
			var data = {boCode : $scope.data.boKey,formType:formType};
			if(treeNode.nodeType=="table"){
				data.tableKey = treeNode.key;
			}else if(treeNode.nodeType=="column"){
				data.tableKey = treeNode.tableKey;
				data.columnKey = treeNode.key;
			}else{
			 	return;
			}
			
			var defer = baseService.postForm(url, data);
			$.getResultData(defer, function(columnHtml) {
				var formItemClass = ".form-item",formItemTitleClass=".form-item-label",formItemContentClass=".form-item-content";
				if(formType=="pc_iview"){
					formItemClass = ".ivu-form-item",formItemTitleClass=".ivu-form-item-label",formItemContentClass=".ivu-form-item-content";
				}
				if(formType=="mobile"){
					formItemClass = ".weui-cell",formItemTitleClass=".weui-label",formItemContentClass=".weui-cell__bd";
				}
			
				var element = editor.selection.getStart();
				// 老版表单 没有 特定的class  
				if($(formItemClass,editor.document).length==0){
					$(element).html($(columnHtml));
					return;
				}
				debugger;
				var formItem = element.closest(formItemClass);
				var tableDiv = element.closest("[table-key]");
				if(!formItem){
					//单行类型的子表，或者特殊类型的子表内部不是布局形式的。直接返回控件
					if(tableDiv && $(tableDiv).attr("table-key")==treeNode.tableKey){
					// 特殊情况。则after
						if($(element).hasClass("readonly-text")){
							$(element).after($(columnHtml));
						}else{
							$(element).html($(columnHtml));
						}
						return;
					}
				
					$.Toast.warning("生成字段前请将光标位于表单 "+treeNode.getParentNode().comment+" 代码块中");
					return;	
				}
				
				if(isMain && tableDiv){
					$.Toast.warning("请将光标位于主表，新字段会生成在光标所在字段后面。");	
					return;			
				}
				if(!isMain && $(tableDiv).attr("table-key")!==treeNode.tableKey){
					$.Toast.warning("请将光标位于"+treeNode.getParentNode().comment+"，新字段会生成在光标所在字段后面。");	
					return;			
				}
			
				var newItem = $(formItem).clone();
				newItem.attr("v-ab-permission:show",$(columnHtml).attr("v-ab-permission"))
				
				$(formItemTitleClass,newItem).html(treeNode.name);
				$(formItemContentClass,newItem).html(columnHtml);
				formItem.after(newItem[0]);
				
				editor.execCommand('inserthtml',"");
			});
		};

		var url = __ctx + "/form/formDef/boTreeData";
		var ztreeCreator = new ZtreeCreator("boTree", url);
		ztreeCreator.setCallback({
			onClick : callBack
		});

		ztreeCreator.initZtree(params);
	});

	/**
	 * 获取获取备份表单信息
	 */
	$scope.getBackupHtml = function() {
		var url = __ctx + "/form/formDef/getBackupHtml";
		var defer = baseService.postForm(url, {
			id : $scope.data.id
		});
		$.getResultData(defer, function(data) {
			$.Toast.success("同步成功");
			$scope.data.html = data;
		});
	};

	/**
	 * 选择模板
	 */
	$scope.selectTemplate = function(tableName) {
		var conf = {
			height : 600,
			width : 800,
			url : "/form/formDef/selectTemplate.html?type=" + formType+"&tableName="+(tableName||""),
			title : "选择模板",
			topOpen : true,
			btn : true,
			closeBtn : 1,
		};
		conf.passData = {
			parentScope : $scope
		};
		conf.ok = function(index, innerWindow) {
			innerWindow.createHtml();
		};
		jQuery.Dialog.open(conf);
	};
} ]);
